﻿using Datav.Design.Service;
using XCode;
using Zdap.Common;
using Zdap.Common.AutoMapper;
using Zdap.Common.Extensions;

namespace Datav.Design.IService
{
    /// <summary>
    ///
    /// </summary>
    public class StudentSubmitService : IStudentGradeDetailService
    {
        private IServiceFactory serviceFactory;

        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceFactory"></param>
        public StudentSubmitService(IServiceFactory serviceFactory)
        {
            this.serviceFactory = serviceFactory;
            // this.taskService = taskService;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async ValueTask<ResponseContext<QuestionDetailDto>> GetQuestionDetail(QuestionSubmitDto model, UserTicket currentUser)
        {
            var rest = new ResponseContext<QuestionDetailDto>();

            var questhion = GetTaskQuestionInfoCache<QuestionDetailDto>(model.QuestionId);

            //查询任务
            //var task = await JxzTask.FindById(model.TaskId);

            if (questhion == null)
            {
                return rest.SetError("未找到题目！");
            }

            if (questhion.IsReadonly == 0)
            {
                questhion.Answer = null;
            }

            //var grade = new StudentGrade();

            var exp = StudentGradeDetail._.QuestionsId == model.QuestionId & StudentGradeDetail._.IsDelete == 0;

            if (model.StudentId > 0)
                exp &= StudentGradeDetail._.UserId == model.StudentId;
            else
            {
                //    grade = await StudentGrade.FindById(model.GradeId);//获取作答主记录
                exp &= StudentGradeDetail._.UserId == currentUser.Id;
                //    if (grade != null)
                //    {
                //        questhion.GradeId = grade.Id;seetionGroupsStatisties:
                //        questhion.IsFulfill = grade.Status == 2 ? true : false;
                //    }
            }

            //if (model.GradeDetailId > 0)
            //    exp &= StudentGradeDetail._.Id == model.GradeDetailId;

            var gradeDetail = await StudentGradeDetail.FindAllAsync(exp, null,
                $"{StudentGradeDetail._.Id},{StudentGradeDetail._.ConfigId},{StudentGradeDetail._.QuestionsId},{StudentGradeDetail._.QuestionType}," +
                $"{StudentGradeDetail._.QuestionParentId},{StudentGradeDetail._.Answer},{StudentGradeDetail._.AnswerCompareInfo}," +
                $"{StudentGradeDetail._.AnswerResult},{StudentGradeDetail._.Score},{StudentGradeDetail._.TeacherComment},{StudentGradeDetail._.Reviewed}", 0, 0);

            //任务答案、分值、错误设置权限控制
            //this.TaskControlSetShow(task, questhion);

            if (gradeDetail.Count() > 0)
            {
                questhion.GradeDetails = gradeDetail.Select(s => s.MapTo<GradeDetail>());
                questhion.IsSubmit = gradeDetail.Any();
                //根据任务控制显示
                //TaskControlSet(task, questhion, gradeDetail);
            }

            rest.SetSuccess(questhion);

            return await Task.FromResult(rest);
        }

        /// <summary>
        /// 查询题目并缓存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static T? GetTaskQuestionInfoCache<T>(long id)
        {
            var exp = Question._.Id == id & Question._.IsDelete == 0;
            var questhionInfo = Question.FindById(id);

            //var questhion = CacheManage.GetCache($"{CacheKeys.Cache_QuestionInfo}{id}", () =>
            //{
            //    var questhionInfo = TaskQuestion.FindById(id);
            //    return questhionInfo != null ? questhionInfo : null;
            //}, CacheKeys.Minute10, true, false);

            return questhionInfo != null ? questhionInfo.MapTo<T>() : default;
        }

        /// <summary>
        /// 提交答案
        /// </summary>
        /// <param name="model"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public Task<ResponseContext<AnswerCompareResultModel>> SubmitAnswer(SubmitAnswerModel model, UserTicket currentUser)
        {
            var service = new StudentSubmitAnswerService(serviceFactory);

            return service.SubmitAnswer(model, currentUser);
        }

        /// <summary>
        /// 删除题目作答记录
        /// </summary>
        /// <param name="gradeDetailId"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public async Task<ResponseContext<bool>> ResettingAnswer(long gradeDetailId, UserTicket currentUser)
        {
            var result = new ResponseContext<bool>();

            var entitys = await StudentGradeDetail.FindAllAsync(StudentGradeDetail._.Id == gradeDetailId & StudentGradeDetail._.UserId == currentUser.Id & StudentGradeDetail._.IsDelete == CommonConstants.IsNotDelete);

            if (entitys.IsNotNullAndEmpty())
            {
                //var taskId = entitys.FirstOrDefault().TaskId;
                //var r = await this.taskService.TaskStatus(taskId);
                // if (r.Data != TaskStatusEnum.Finish)
                {
                    int i = entitys.Delete();
                    if (i > 0)
                    {
                        result.SetSuccess(true);
                    }
                }
                //else
                //{
                //    result.SetError("任务已经结束,不能重置答案！");
                //}
            }
            return await Task.FromResult(result);
        }
    }
}